#include <stdio.h>
#include <curl/curl.h>
#include <glib.h>
#include <stdlib.h>
#include <string.h>
#include <json/json.h>

const char* ReturnJsonValue(json_object *value){
	g_print("json value is: %s\n",json_object_to_json_string(value));
	return json_object_to_json_string(value);
}

GString *CreateJsonValue(){
        GString *result  = g_string_new(NULL);;
	json_object *json_obj = json_object_new_object();
	json_object_object_add(json_obj,"requestType",json_object_new_string("Linux Ubuntu 14\.04 Dolphin Client"));

	json_object *requestbody = json_object_new_object();
	json_object_object_add(requestbody,"name",json_object_new_string("tang"));

	json_object_object_add(json_obj,"data",requestbody);

        g_string_printf(result,"%s",ReturnJsonValue(json_obj));

	ReturnJsonValue(json_obj);
	//g_print("%s\n",g_string_free(result,FALSE));
	//exit(EXIT_FAILURE);

        return result;
}

typedef struct string {
  char *ptr;
  size_t len;
} String;

void init_string(struct string *s) {
  s->len = 0;
  s->ptr = malloc(s->len+1);
  if (s->ptr == NULL) {
    fprintf(stderr, "malloc() failed\n");
    exit(EXIT_FAILURE);
  }
  s->ptr[0] = '\0';
}

size_t writefunc(void *ptr, size_t size, size_t nmemb, struct string *s)
{
  size_t new_len = s->len + size*nmemb;
  s->ptr = realloc(s->ptr, new_len+1);
  if (s->ptr == NULL) {
    fprintf(stderr, "realloc() failed\n");
    exit(EXIT_FAILURE);
  }
  memcpy(s->ptr+s->len, ptr, size*nmemb);
  s->ptr[new_len] = '\0';
  s->len = new_len;

  return size*nmemb;
}

int main(void)
{
  CURL *curl;
  CURLcode res;

  curl_global_init(CURL_GLOBAL_DEFAULT);

  curl = curl_easy_init();
  if(curl) {
    struct string s;
    init_string(&s);

    struct curl_slist *headers = NULL;
    headers = curl_slist_append(headers, "Content-Type: application/json");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

    curl_easy_setopt(curl, CURLOPT_URL, "localhost:8080/person/json");

    GString *json_string = CreateJsonValue();
    
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, g_string_free(json_string,FALSE));

    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
    /* Perform the request, res will get the return code */
    res = curl_easy_perform(curl);
    /* Check for errors */
    if(res != CURLE_OK)
      fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));

    printf("%s\n",s.ptr);
    curl_easy_cleanup(curl);
  }

  curl_global_cleanup();

  return 0;
}
